package com.giantlizard.cloud.auth.service.impl;

import com.giantlizard.cloud.auth.model.LoginDTO;
import com.giantlizard.cloud.auth.service.AuthService;
import com.giantlizard.cloud.base.generics.R;
import com.giantlizard.cloud.common.security.model.LoginUser;
import com.giantlizard.cloud.common.security.service.TokenService;
import com.giantlizard.cloud.common.security.utils.SecurityUtils;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.crypto.SecretKey;

import java.util.Base64;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

@Service
@Slf4j
public class AuthServiceImpl implements AuthService {

    @Autowired
    private AuthenticationManager authenticationManager;
    
    @Autowired
    private TokenService tokenService;

    @Override
    public R<?> login(LoginDTO loginDTO) {
        try {
            // 1. 执行认证
            Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginDTO.getUsername(), loginDTO.getPassword())
            );
            // 2. 生成token
            LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            String token = tokenService.createToken(loginUser);
            return R.ok(token);
        } catch (BadCredentialsException e) {
           log.error(e.getMessage());
            return R.error("用户名或密码错误");
        } catch (Exception e) {
            log.error(e.getMessage());
            return R.error("登录失败：" + e.getMessage());
        }
    }

    @Override
    public R<?> logout() {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser != null) {
                tokenService.delLoginUser(loginUser.getToken());
            }
            return R.ok();
        } catch (Exception e) {
            return R.error("登出失败：" + e.getMessage());
        }
    }

} 